#!/usr/bin/perl -w
use strict;
use diagnostics;
use diagnostics -verbose;
my $target = "./target";
sub copy_target {
    my($path) = @_;
    my @levels = split(/\//, $path);
    $#levels -= 1;
    my $dp = $target . join("/", @levels);

    qx { mkdir -pv $dp };

    print "mkdir: $dp\n";
    my $dest = $target . $path;
    print "copy $path to $dest\n";
    qx { cp -Pfv $path $dest };
}

sub trace_link {
    my($path) = @_;
    my @levels = split(/\//, $path);
    $#levels -= 1;
    my $dp = join("/", @levels);
    my @real = qx { readlink $path };
    if (@real) {
        my @c = split (//, $real[0]);
        if ($c[0] eq '/') {
            print "Hi it's absolute path!\n";
            $real[0] = $real[0];
        } else {
            $real[0] = $dp . "/$real[0]";
        }
        return $real[0];
    }
}
my $filename;
if (@ARGV == 0) {
    print "Give me a file\n";
    print "command [filename]\n";
    $filename = `whereis mplayer`;
    my @files = split(/ /, $filename);
    if (scalar @files == 1) {
        print "File not found!";
        exit -1;
    }
    $filename = $files[1];
    print "I am going to use [$filename] \n";
} else {
    $filename = $ARGV[0];
}
my @results = qx{ ldd $filename };
my $line;
foreach $line (@results) {
    chomp $line;
    print "[ $line ]\n";
    my (@tokens, $name);
    @tokens = split(/\s+/, $line);

    print "tokens number:". @tokens . "\n";
    if( @tokens == 4) {
        print "I am going to next loop.\n";
        next;
    } elsif( @tokens == 3) {
        $name = $tokens[1];
    } elsif( @tokens == 5) {
        $name = $tokens[3]; 
    } else {
        print "I cannot recognize this format. contact author now!";
        exit -1;
    }

    while ($name) {
        chomp $name;
        print "Source: $name \n";
        copy_target($name);
        $name = trace_link($name);
    }
}
print "copy $filename $target \n";
qx { cp -Pfv $filename $target };
